//
//  ICChatViewController+Delegate.m
//  ICome
//
//  Created by zhangrongwu on 2016/11/18.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICChatViewController+Delegate.h"
#import "ICFaceManager.h"
#import "ICChatNetworkManager.h"
#import "ICNavigationController.h"
#import "ICFileTool.h"
#import "ICChatAdaptBaseCell.h"
#import "iComeApiManager.h"
@implementation ICChatViewController (Delegate)
- (void)didClickPendingSureBtnInCell:(ICGtasksTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    // 对中间层进行转换
    ICMessageFrame *modelFrame = self.dataSource[indexPath.row];
    ICGtasksModel *model = [ICMessageHelper getGtasksModelWith:modelFrame.model.message];
    NSString *url = [model appendUserInfoforJSURL:model.confirmurl msgId:model.msgId];
    [MBProgressHUD showMessage:@"正在处理" toView:self.view];
    [[ICApplicationNetworkManager sharedInstance] gtaskConfirmurl:url success:^(id object) {
        [MBProgressHUD hideHUDForView:self.view];
        [ICMessageDatabase setGtasksMsgId:model.msgId Status:[NSString stringWithFormat:@"%d", TodoStatus_Confirm]]; // 数据库变动
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"提交失败"];
    }];
}


- (void)didClickPendingCancelBtnInCell:(ICGtasksTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ICMessageFrame *modelFrame = self.dataSource[indexPath.row];
    ICGtasksModel *model = [ICMessageHelper getGtasksModelWith:modelFrame.model.message];
    
    NSString *url = [model appendUserInfoforJSURL:model.rejecturl msgId:model.msgId];
    [MBProgressHUD showMessage:@"正在处理" toView:self.view];
    [[ICApplicationNetworkManager sharedInstance] gtaskRejecturl:url success:^(id object) {
        [MBProgressHUD hideHUDForView:self.view];
        [ICMessageDatabase setGtasksMsgId:model.msgId Status:[NSString stringWithFormat:@"%d", TodoStatus_Reject]];
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"提交失败"];
    }];
}

- (void)didClickPendingDetailBtnInCell:(ICGtasksTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ICMessageFrame *modelFrame = self.dataSource[indexPath.row];
    ICGtasksModel *model = [ICMessageHelper getGtasksModelWith:modelFrame.model.message];
    if (![ICTools stringEmpty:model.openurl]) {
        [self pushCustomViewControllerURL:model.openurl fromViewController:self animated:YES];
    }
}


#pragma mark - baseCell delegate

- (void)longPress:(UILongPressGestureRecognizer *)longRecognizer
{
    if (longRecognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint location       = [longRecognizer locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
        self.longIndexPath     = indexPath;
        id object              = [self.dataSource objectAtIndex:indexPath.row];
        if (![object isKindOfClass:[ICMessageFrame class]]) return;
       UITableViewCell *kCell = [self.tableView cellForRowAtIndexPath:indexPath];
        if ([kCell isKindOfClass:[ICChatAdaptBaseCell class]]) {
            ICChatAdaptBaseCell *cell = (ICChatAdaptBaseCell *)kCell;
            ICMessageFrame *messageFrame = (ICMessageFrame *)object;
            [self showMenuViewController:cell andIndexPath:indexPath message:messageFrame.model];
        } else if ([kCell isKindOfClass:[ICChatMessageBaseCell class]]) {
            ICChatMessageBaseCell *cell = (ICChatMessageBaseCell *)kCell;
            [self showMenuViewController:cell.bubbleView andIndexPath:indexPath message:cell.modelFrame.model];
        }
    }
}

- (void)headImageClicked:(NSString *)eId
{
    NSDictionary *param = @{@"eId":eId};
    if ([eId rangeOfString:@"bot"].location == NSNotFound) {
        if([eId isEqualToString:[ICUser currentUser].eId]){
            if ([[iComeApiManager instance].delegate respondsToSelector:@selector(openContactsDetailsFromViewC::)]) {
                [[iComeApiManager instance].delegate openContactsDetailsFromViewC:self:param];
            }
        }else{
            
            if ([[iComeApiManager instance].delegate respondsToSelector:@selector(openContactsDetailsFromViewC::)]) {
                [[iComeApiManager instance].delegate openContactsDetailsFromViewC:self:param];
            } else {
                UIViewController * vc = [[IComMediator sharedInstance] IComMediator_ContactsDetailViewController:param];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    }else
    {
        UIViewController *vc = [[IComMediator sharedInstance] IComMediator_RobotDetailViewController:param];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
// 消息重发机制
- (void)reSendMessage:(ICChatMessageBaseCell *)baseCell
{
    ICMessageFrame *messageF = baseCell.modelFrame;
    messageF.model.message.deliveryState = ICMessageDeliveryState_Delivering;
    messageF.model.message.reSend++;
    messageF.model.message.isAnimation = YES;
    [self reloadTableView];
    if ([messageF.model.message.type isEqualToString:TypeText]) {
        [self sendTextMessage:messageF.model.message.content messageF:messageF];
    } else if ([messageF.model.message.type isEqualToString:TypeAtText]) { // @
        [self sendTextMessage:messageF.model.message.content messageF:messageF];
    } else if ([messageF.model.message.type isEqualToString:TypeVoice]) {
        NSString *voicePath = [self mediaPath:messageF.model.mediaPath];
        NSString *amrPath   = [[voicePath stringByDeletingPathExtension] stringByAppendingPathExtension:kAccType];
        [self sendVoiceMessage:amrPath messageF:messageF];
    } else if ([messageF.model.message.type isEqualToString:TypePic]) {
        NSString *path = [[ICMediaManager sharedManager] getLocationImagePath:[messageF.model.mediaPath lastPathComponent]];
        if (![ICFileTool fileExistsAtPath:path]) { // 本地不存在逻辑
            if (![ICTools stringEmpty:messageF.model.message.fileKey]) {
                // 正常逻辑
                ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                                 Message:TypePic
                                                                 content:messageF.model.message.content
                                                                 fileKey:messageF.model.message.fileKey
                                                                    from:[ICUser currentUser].eId
                                                                      to:self.group.gId
                                                                     lnk:messageF.model.message.lnk
                                                                  status:nil];
                [self sendMessage:message messageF:messageF];
            } else {
                [self messageSendFailued:messageF];
            }
        } else {
            [self sendImageMessage:path messageF:messageF];
        }
    } else if ([messageF.model.message.type isEqualToString:TypeVideo]) {
        NSString *mp4Path  = [self videoPath:messageF];
        if (![ICFileTool fileExistsAtPath:mp4Path]) { // 本地不存在逻辑
            if (![ICTools stringEmpty:messageF.model.message.fileKey]) {
                // 正常逻辑
                ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                                 Message:TypeVideo
                                                                 content:messageF.model.message.content
                                                                 fileKey:messageF.model.message.fileKey
                                                                    from:[ICUser currentUser].eId
                                                                      to:self.group.gId
                                                                     lnk:messageF.model.message.lnk
                                                                  status:nil];
                [self sendMessage:message messageF:messageF];
            } else {
                [self messageSendFailued:messageF];
            }
        } else {
            [self sendVideoMessage:mp4Path messageF:messageF];
        }
    } else if ([messageF.model.message.type isEqualToString:TypeFile]) {
        NSString *path = [self localFilePath:messageF];
        if (![ICFileTool fileExistsAtPath:path]) { // 本地不存在文件逻辑
            if (![ICTools stringEmpty:messageF.model.message.fileKey]) {
                // 正常逻辑
                ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                                 Message:TypeFile
                                                                 content:messageF.model.message.content
                                                                 fileKey:messageF.model.message.fileKey
                                                                    from:[ICUser currentUser].eId
                                                                      to:self.group.gId
                                                                     lnk:messageF.model.message.lnk
                                                                  status:nil];
                [self sendMessage:message messageF:messageF];
            } else {
                [self messageSendFailued:messageF];
            }
        } else {// 本地存在文件逻辑
            [self sendFile:messageF path:path];
        }
    } else if ([messageF.model.message.type isEqualToString:TypeRedPacket]) {
        ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                         Message:TypeRedPacket
                                                         content:messageF.model.message.content
                                                         fileKey:messageF.model.message.fileKey
                                                            from:[ICUser currentUser].eId
                                                              to:self.group.gId
                                                             lnk:messageF.model.message.content
                                                          status:nil];
        [self sendMessage:message messageF:messageF];
    } else if ([messageF.model.message.type isEqualToString:TypeDrtNews]) { // 送达号
        ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                         Message:TypeDrtNews
                                                         content:messageF.model.message.content
                                                         fileKey:messageF.model.message.fileKey
                                                            from:[ICUser currentUser].eId
                                                              to:self.group.gId
                                                             lnk:messageF.model.message.lnk
                                                          status:nil];
        [self sendMessage:message messageF:messageF];
    } else if ([messageF.model.message.type isEqualToString:TypeVideoConference]) { // 视频会议
        ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                         Message:TypeVideoConference
                                                         content:messageF.model.message.content
                                                         fileKey:messageF.model.message.fileKey
                                                            from:[ICUser currentUser].eId
                                                              to:self.group.gId
                                                             lnk:messageF.model.message.lnk
                                                          status:nil];
        [self sendMessage:message messageF:messageF];
    }
}


- (void)showMenuViewController:(UIView *)showInView andIndexPath:(NSIndexPath *)indexPath message:(ICMessageModel *)messageModel
{
    if ([messageModel.message.type isEqualToString:TypeQuestion]) {
        return;
    }
    
    if (_copyMenuItem   == nil) {
        _copyMenuItem   = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyMessage:)];
    }
    if (_deleteMenuItem == nil) {
        _deleteMenuItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteMessage:)];
    }
    if (_forwardMenuItem == nil) {
        _forwardMenuItem = [[UIMenuItem alloc] initWithTitle:@"转发" action:@selector(forwardMessage:)];
    }
    if (_collectMenuItem == nil) {
        _collectMenuItem = [[UIMenuItem alloc] initWithTitle:@"提醒" action:@selector(collectionMessage:)];
    }
    NSInteger currentTime = [ICMessageHelper currentMessageTime];
    NSInteger interval    = currentTime - messageModel.message.date;
    
    if (messageModel.isSender) {
        if ((interval/1000) < 5*60 && !(messageModel.message.deliveryState == ICMessageDeliveryState_Failure)) {
            if (_recallMenuItem == nil) {
                _recallMenuItem = [[UIMenuItem alloc] initWithTitle:@"撤回" action:@selector(recallMessage:)];
            }
            [[UIMenuController sharedMenuController] setMenuItems:@[_copyMenuItem,_deleteMenuItem,_recallMenuItem,_forwardMenuItem,_collectMenuItem]];
        } else {
            [[UIMenuController sharedMenuController] setMenuItems:@[_copyMenuItem,_deleteMenuItem,_forwardMenuItem,_collectMenuItem]];
        }
    } else {
        [[UIMenuController sharedMenuController] setMenuItems:@[_copyMenuItem,_deleteMenuItem,_forwardMenuItem,_collectMenuItem]];
    }
    // 删除
    if ([messageModel.message.type isEqualToString:TypeVideoConference]||[messageModel.message.type isEqualToString:TypeSysTop]) {
        [[UIMenuController sharedMenuController] setMenuItems:@[_deleteMenuItem]];
    }

    if ([messageModel.message.type isEqualToString:TypeTextURL]) {
        [[UIMenuController sharedMenuController] setMenuItems:@[_copyMenuItem,_deleteMenuItem,_forwardMenuItem]];
    }
    // 发送失败
    if (messageModel.message.deliveryState != ICMessageDeliveryState_Delivered) {
        [[UIMenuController sharedMenuController] setMenuItems:@[_deleteMenuItem]];
    }
    
    [[UIMenuController sharedMenuController] setTargetRect:showInView.frame inView:showInView.superview ];
    [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
}

- (void)copyMessage:(UIMenuItem *)copyMenuItem
{
    UIPasteboard *pasteboard  = [UIPasteboard generalPasteboard];
    ICMessageFrame * messageF = [self.dataSource objectAtIndex:self.longIndexPath.row];
    pasteboard.string  = messageF.model.message.content;
}

- (void)forwardMessage:(UIMenuItem *)forwardMenuItem
{
    ICMessageFrame *messageF = [self.dataSource objectAtIndex:self.longIndexPath.row];
    ICMessageForwardController *forVC = [[ICMessageForwardController alloc] init];
    forVC.delegate = self;
    ICNavigationController * nav = [[ICNavigationController alloc] initWithRootViewController:forVC];
    forVC.messageModelsArray = @[messageF];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

- (void)collectionMessage:(UIMenuItem *)collectionMenuItem
{
    return;
    ICMessageFrame *messageF  = [self.dataSource objectAtIndex:self.longIndexPath.row];
    NSString *photoId = [ICMessageDatabase getPhotoIdWithEId:messageF.model.message.from];
    NSString *name  = [ICMessageDatabase getUserNameWithEId:messageF.model.message.from];
    
    NSString *title = [NSString stringWithFormat:@"%@-%@", self.title,name];
    // 收藏
    NSString * photoId1 = ![ICTools stringEmpty:photoId] ? photoId:[NSString stringWithFormat:@"eId:%@",messageF.model.message.from];
    NSString *gId = self.group.gId;
    
    if ([messageF.model.message.type isEqualToString:TypeDrtNews]) {
        NSDictionary *dict = [NSDictionary dictionaryWithJsonString:messageF.model.message.fileKey];
        gId = dict[@"did"] == nil ? self.group.gId : dict[@"did"];
    }
    NSDictionary *param = [ICMessageHelper createCollectMessage:messageF.model.message.type
                                                            eId:[ICUser currentUser].eId
                                                            gId:gId
                                                        photoId:photoId1
                                                        msgId:messageF.model.message.messageId
                                                          title:title
                                                            txt:messageF.model.message.content
                                                            key:messageF.model.message.fileKey
                                                            lnk:messageF.model.message.lnk];
    if (![ICTools stringEmpty:messageF.model.message.content]) {
        if ([ICFaceManager isContainsEmoji:messageF.model.message.content]) {
            [MBProgressHUD showError:@"暂不支持收藏表情符号"];
            return;
        }
    }
    [[ICChatNetworkManager sharedInstance] addFavoriteWithParam:param Success:^(id object) {
        [MBProgressHUD showSuccess:@"收藏成功"];
    } failure:^(NSError *error) {
        [MBProgressHUD showError:error.domain];
    }];
}

- (void)recallMessage:(UIMenuItem *)recallMenuItem
{
    ICMessageFrame * messageF = [self.dataSource objectAtIndex:self.longIndexPath.row];
    if (messageF.model.message.deliveryState == ICMessageDeliveryState_Failure){
        [self statusChanged:messageF];
        return;
    }
    [MBProgressHUD showMessage:@"" toView:self.view];
    NSDictionary *param = @{
                            @"gId":messageF.model.message.to,
                            @"msgId" :messageF.model.message.messageId
                            };
    
    [[ICSocketRequestManager sharedInstance] recallMessageWithObject:param Success:^(id response) {
        
        [self statusChanged:messageF];
        [ICMessageDatabase messageBackAction:self.group.gId messageId:messageF.model.message.messageId lastMsgTime:messageF.model.message.date];
        ICMessageFrame *msgF = [ICMessageDatabase getMessage:self.group.gId msgId:messageF.model.message.messageId];
        [self.dataSource insertObject:msgF atIndex:self.longIndexPath.row];
        [self.tableView reloadData];
        [MBProgressHUD hideHUDForView:self.view];
    } Failure:^(NSError *error, id other) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:error.domain];
        NSLog(@"ICRecallMsg request error:%@",error);
    }];
}

- (void)deleteMessage:(UIMenuItem *)deleteMenuItem
{
    ICMessageFrame * messageF = [self.dataSource objectAtIndex:self.longIndexPath.row];
    [self statusChanged:messageF]; // 删除的消息我也按撤回的状态进行处理
}

// 文件路径
- (NSString *)mediaPath:(NSString *)originPath
{
    // 这里文件路径重新给，根据文件名字来拼接
    NSString *name = [[originPath lastPathComponent] stringByDeletingPathExtension];
    return [[ICRecordManager shareManager] receiveVoicePathWithFileKey:name];
}

#pragma mark - ICPubMenuViewDelegate

- (void)clickItemURL:(NSString *)url {
    [self pushCustomViewControllerURL:url fromViewController:self animated:YES];
}

#pragma mark - UIGestureRecognizerDelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return YES;
}

#pragma ICTransferCustomerViewDelegate
- (void)sureTransferCustomer:(id)customer {
    NSDictionary *param = @{@"freId":[ICUser currentUser].eId,
                            @"gId":self.group.gId,
                            @"toeId":customer};
    [[ICChatNetworkManager sharedInstance] transferCustomerWithParam:param Success:^(id object) {
        [MBProgressHUD showSuccess:@"转出会话成功"];
    } failure:^(NSError *error) {
        [MBProgressHUD showError:error.domain];
    }];
}

#pragma mark - DetailDeletage
// 清空聊天信息
- (void)recordDidCleared
{
    ICMessageFrame *lastMessageF = [self.dataSource lastObject];
    ICMessage *message = lastMessageF.model.message;
    
    // 正常保存最后一条消息到 消息组表中
    [ICMessageDatabase updateGroupLastMessageTime:message.to lastMsgTime:message.date lastMsgTxt:@"" lastMsgId:message.messageId lastChangeId:message.from];
    
    [self.dataSource removeAllObjects];
    [self.tableView reloadData];
}
#pragma mark ICMessageForwardControllerDelegate
- (void)frowardSendMessageSuccessgId:(NSString *)gId {
    if ([self.group.gId isEqualToString:gId]) {
        [self.dataSource removeAllObjects];
        [self loadDataSource];
        NSLog(@"发送成功%@", gId);
    }
}
#pragma mark ChatMessageTopViewDelegate
- (void)clickTopMessage:(NSString *)url {
    if(url) {
        [self pushCustomViewControllerURL:url fromViewController:self animated:YES];
    }
}

- (void)deleteTopMessage {
    self.topMessageView.height = 0;
    self.topMessageView.hidden = YES;
    [self setupUI];
}
@end







